package com.yntx.usercenter.common.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * redis template 配置
 *
 * @author jielihaofeng
 * @date 2023-04-24 14:37
 */
@Configuration
public class RedisTemplateConfiguration {

    @Bean
    public StringRedisSerializer stringRedisSerializer() {
        return new StringRedisSerializer();
    }

    @Bean
    public Jackson2JsonRedisSerializer<Object> objectJackson2JsonRedisSerializer() {
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        return jackson2JsonRedisSerializer;
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory connectionFactory) {

        RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
        // key使用String序列化
        redisTemplate.setKeySerializer(stringRedisSerializer());
        redisTemplate.setHashKeySerializer(stringRedisSerializer());
        // value使用Jackson2JsonRedisSerialize 替换默认序列化(默认采用的是JDK序列化)
        redisTemplate.setValueSerializer(objectJackson2JsonRedisSerializer());
        redisTemplate.setHashValueSerializer(objectJackson2JsonRedisSerializer());
        redisTemplate.setConnectionFactory(connectionFactory);
        redisTemplate.afterPropertiesSet();

        return redisTemplate;
    }

//    @Bean
//    public RedisTemplate<String, String> stringRedisTemplate(RedisConnectionFactory connectionFactory) {
//
//        RedisTemplate<String, String> redisTemplate = new StringRedisTemplate();
//        // key使用String序列化
//        redisTemplate.setKeySerializer(stringRedisSerializer());
//        redisTemplate.setHashKeySerializer(stringRedisSerializer());
//        redisTemplate.setValueSerializer(objectJackson2JsonRedisSerializer());
//        // value使用Jackson2JsonRedisSerialize 替换默认序列化(默认采用的是JDK序列化)
//        redisTemplate.setHashValueSerializer(objectJackson2JsonRedisSerializer());
//        redisTemplate.setConnectionFactory(connectionFactory);
//        redisTemplate.afterPropertiesSet();
//
//        return redisTemplate;
//    }

}
